from django.db import models
from crm.constants import * 
from django.contrib.auth.models import User

# Create your models here.

class TimeAuditModel(models.Model):
    """To path when the record was created and last modified"""

    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="Created At",
    )
    updated_at = models.DateTimeField(
        auto_now=True, verbose_name="Last Modified At")

    class Meta:
        abstract = True


# Choices for gender
class GenderChoices(models.IntegerChoices):
    Male = 1
    Female = 2
    unknow = 3


class Company(models.Model):
    name = models.CharField(max_length=50, verbose_name="名称")
    mainbusiness = models.CharField(max_length=50, verbose_name="行业")
    scale = models.CharField(
        max_length=2, choices=SCALE_CHOICES, default='UN', verbose_name="规模")
    address = models.CharField(
        max_length=100, blank=True, null=True, verbose_name="地址")  # Field name

    def __str__(self):
        return f"{self.name}, {self.mainbusiness}, {self.scale}"

    class Meta:
        managed = True
        db_table = 'company'
        verbose_name = '公司'
        verbose_name_plural = verbose_name
        ordering = ['name']


# 客户信息模型（保存客户信息）
class Account(models.Model):
    name = models.CharField(max_length=50,verbose_name="客户名称")
    cust_no = models.CharField(max_length=10,null=True,unique=True,verbose_name="客户编号")
    type = models.CharField(max_length=50,null=True,choices=ACCOUNT_TYPE_CHOICES,default="NORMAL_ACCOUNT",verbose_name="客户类型")
    industry = models.CharField(max_length=50,null=True,choices=INDUSTRY_CHOICES,default="Others" ,verbose_name="所属行业")
    scale = models.CharField(
        max_length=2, choices=SCALE_CHOICES, null=True,default='UN', verbose_name="客户规模")
    country = models.CharField(max_length=50, null=True, verbose_name="国家")
    province = models.CharField(max_length=50,null=True,verbose_name="省份")
    city = models.CharField(max_length=50, null=True,verbose_name="城市")
    post_code = models.CharField(
        max_length=15, blank=True, null=True, verbose_name="邮编")
    address = models.CharField(max_length=100,null=True ,verbose_name="详细地址")  # Field name
    finance_account = models.CharField(
        max_length=50, null=True ,verbose_name="财务账号")
    credit_quota = models.IntegerField(default=0 ,verbose_name="信用额度")
    phone = models.CharField(max_length=20,null=True,blank=True ,verbose_name="电话")
    email = models.EmailField(max_length=50,null=True,blank=True,verbose_name="电子邮件")
    website = models.CharField(max_length=100,null=True,blank=True,verbose_name="官方网站")

    def __str__(self):
        return f"{self.name},{self.industry} ,{self.city}, {self.type}"

    class Meta:
        managed = True
        db_table = 'account'
        verbose_name = '客户池'
        verbose_name_plural = verbose_name

# 联系人模型
class Contact(models.Model):
    name = models.CharField(max_length=50, verbose_name="姓名")
    gender = models.SmallIntegerField(
        choices=GenderChoices.choices, default=3, verbose_name="性别")
    account = models.ForeignKey(Account, on_delete=models.CASCADE,related_name='contacts')
    dept = models.CharField(max_length=30,blank=True, null=True, verbose_name="部门")
    title = models.CharField(max_length=20,blank=True, null=True, verbose_name="职位")
    phone = models.CharField(max_length=20,blank=True, null=True, verbose_name="电话")
    email = models.EmailField(max_length=50,blank=True, null=True, verbose_name="电子邮件")
    wechat  = models.CharField(max_length=80,blank=True, null=True, verbose_name="微信号")
    is_decisor = models.BooleanField(default=False, verbose_name="是否决策人")
    description = models.TextField(max_length=300,blank=True, null=True, verbose_name="简介")

    def __str__(self) -> str:
        return f"{self.name}-{self.account.name}-{self.title}"
    
    class Meta:
        managed = True
        db_table = 'contact'
        verbose_name = '联系人'
        verbose_name_plural = verbose_name

# 销售机会模型
class BizOpp(TimeAuditModel):
    name = models.CharField(max_length=64,unique=True,verbose_name='机会名称')
    account = models.ForeignKey(
        Account,
        related_name="opps",
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name="关联客户"
    )
    contact = models.ForeignKey('Contact', related_name='opps',on_delete=models.CASCADE,verbose_name="联系人")
    value = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True, verbose_name="金额")
    lead_source = models.CharField(max_length=100, choices=OPP_SOURCES, blank=True, null=True,verbose_name="机会来源")
    probability = models.IntegerField(default=0,blank=True, null=True, verbose_name="机率")
    owner = models.ForeignKey(
        "Employee", on_delete=models.SET_NULL, blank=True, null=True,related_name="opps" ,verbose_name="负责人")
    owner_dept = models.ForeignKey(
        "Companydept", on_delete=models.SET_NULL, blank=True, null=True,related_name="opps", verbose_name="归属部门")
    closed_expect = models.DateField(blank=True, null=True,verbose_name="预计成交日期")
    description = models.TextField(blank=True, null=True, verbose_name="描述")
    stage = models.CharField(
        max_length=20, choices=STAGES, blank=True, null=True,verbose_name="销售阶段")
    closed_at = models.DateField(blank=True, null=True)

    def __str__(self):
        return f"{self.name} - {self.value} - {self.lead_source}"

    class Meta:
        managed = True
        db_table = 'biz_opp'
        verbose_name = '销售机会'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['name'], name='bizopp_name_idx'),
        ]
        ordering = ["-created_at"]


# 老的客户模型
class Customers(models.Model):
    name = models.CharField(max_length=50, verbose_name="姓名")
    gender = models.SmallIntegerField(
        choices=GenderChoices.choices, default=3, verbose_name="性别")
    age = models.IntegerField(blank=True, null=True, verbose_name="年龄")
    company = models.ForeignKey(
        Company, on_delete=models.CASCADE, related_name="customers")
    phone = models.CharField(max_length=30, verbose_name="电话")
    # Field name made lowercase.
    address = models.CharField(
        max_length=100, blank=True, null=True, verbose_name="地址")
    city = models.CharField(max_length=50, verbose_name="城市")
    # Field name made lowercase.
    postcode = models.CharField(
        max_length=15, blank=True, null=True, verbose_name="邮编")
    country = models.CharField(max_length=50, verbose_name="国家")
    creditlimit = models.DecimalField(
        max_digits=10, decimal_places=2, blank=True, null=True, verbose_name="信用额")

    def __str__(self):
        return f"{self.name} - {self.company} - {self.city}"

    class Meta:
        managed = True
        db_table = 'customers'
        verbose_name = '客户（old)'
        verbose_name_plural = verbose_name
        ordering = ['company', 'name']

# 老的销售机会模型
class Opportunity(TimeAuditModel):
    name = models.CharField(max_length=64, verbose_name='机会名称')
    company = models.ForeignKey(
        "Company",
        related_name="opportunities",
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    amount = models.DecimalField(
        "Opportunity Amount", decimal_places=2, max_digits=12, blank=True, null=True
    )
    lead_source = models.CharField(
        "Source of Lead", max_length=100, choices=OPP_SOURCES, blank=True, null=True
    )
    probability = models.IntegerField(default=0, blank=True, null=True)
    owner = models.ForeignKey(
        "Employee", on_delete=models.SET_NULL, blank=True, null=True,related_name='opportunitys')
    contacts = models.ManyToManyField('Customers', related_name='opportunitys')
    description = models.TextField(blank=True, null=True)
    status = models.CharField(
        max_length=20, choices=OPP_STATUS_CHOICES, blank=True, null=True)
    closed_at = models.DateField(blank=True, null=True)

    def __str__(self):
        return f"{self.name} - {self.amount} - {self.lead_source}"

    class Meta:
        managed = True
        db_table = 'opportunity'
        verbose_name = '销售机会(old)'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['name'], name='name_idx'),
        ]
        ordering = ["-created_at"]

# Employee 员工模型
class Employee(models.Model):
    name = models.CharField(max_length=30, unique=True, verbose_name="姓名")
    gender = models.SmallIntegerField(
        choices=GenderChoices.choices, default=3, verbose_name="性别")
    birthday = models.DateField(blank=True, null=True, verbose_name="生日")
    phone = models.CharField(max_length=30, verbose_name="电话")          
    user = models.OneToOneField(
                                User,
                                to_field="username", 
                                on_delete=models.CASCADE, 
                                related_name='employee',
                                verbose_name='账号'
                                )
    email =  models.EmailField(max_length=254, verbose_name="邮箱")
    dept = models.ForeignKey(
                            "Companydept", 
                            on_delete = models.SET_NULL, 
                            null=True, 
                            blank=True,
                            verbose_name='部门',
                            related_name= 'employees'
                            )  
    jobtitle = models.CharField(db_column='jobTitle', max_length=50,
                                blank=True, verbose_name='职务')
    is_valid = models.BooleanField(default=False, verbose_name='有效')
    
    def __str__(self):
        dept_str = getattr(self.dept, 'levelOneDept', '未分配部门')
        return f"id: {self.id}, name: {self.name}, dept: {dept_str}"

    class Meta:
        managed = True 
        db_table = 'employee'
        verbose_name = '员工信息'
        verbose_name_plural = verbose_name  
            

# 部门信息模型
class Companydept(models.Model):
    levelOneDept = models.CharField(max_length=30, verbose_name='一级部门名称')
    levelTwoDept = models.CharField(max_length=30, verbose_name='二级部门名称')
    def __str__(self):
        return f"Companydept ID: {self.id}, level-1: {self.levelOneDept}, level-2: {self.levelTwoDept}"
    
    class Meta:
        managed = True
        db_table = 'companydept'
        verbose_name = '部门信息'
        verbose_name_plural = '部门信息'

# 产品线信息模型
class ProductLine(models.Model):
    name = models.CharField(max_length=30, verbose_name='产品线名称')
    description = models.TextField(blank=True, null=True, verbose_name='描述')

    def __str__(self):
        return f"ProductLine ID: {self.id}, name: {self.name}"
    
    class Meta:
        managed = True
        db_table = 'productline'
        verbose_name = '产品线信息'
        verbose_name_plural = verbose_name


# 销售记录表
class Deal(models.Model):    
    order_number = models.CharField(max_length=30, verbose_name='订单编号')
    contract = models.CharField(max_length=30, verbose_name='合同编号')
    title = models.CharField(max_length=100,null=True,verbose_name='合同名称')
    date = models.DateField(verbose_name='销售日期')
    total_amount = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='总金额')
    account = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True, related_name="deals")
    opportunity = models.ForeignKey('Opportunity', on_delete=models.SET_NULL, null=True,related_name="deals")
    employee = models.ForeignKey('Employee', on_delete=models.SET_NULL, null=True, related_name="deals")

    def __str__(self):
        return f"Deal ID: {self.id}, order_number: {self.order_number}"
    
    class Meta:
        managed = True
        db_table = 'deal'
        verbose_name = '销售记录'
        verbose_name_plural = verbose_name


# 客户沟通记录表
class Communication(models.Model):
    description = models.TextField(blank=True, null=True)
    communicate_date = models.DateField()
    outcome = models.CharField(max_length=150, blank=True, null=True)
    account = models.ForeignKey('Account', on_delete=models.SET_NULL, null=True)
    contact = models.ManyToManyField('Contact')
    employee = models.ForeignKey('Employee', on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return f"Communication ID: {self.id}, description: {self.description}"
    
    class Meta:
        managed = True
        db_table = 'communication'
        verbose_name = '客户沟通记录'
        verbose_name_plural = verbose_name
